package com.cecsmsserve.util;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import static cn.hutool.core.date.DateUnit.*;

public class JWTUtil {
    /**
     * 密钥要自己保管好
     */
    static String SECRET = "!Q@W#E$R";
//
//    public static String buildToken(HashMap<String, String> map) throws UnsupportedEncodingException {
//        JWTCreator.Builder builder = JWT.create();
//        //payload
//        map.forEach((k,v)->{
//            builder.withClaim(k,v);
//        });
//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.HOUR, 1); //默认1小时过期
//        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
////        builder.withExpiresAt(DateUnit.offsetHour(new Date(),2));//2小时后token过期
//        return builder.sign(Algorithm.HMAC256(SECRET));
//    }

    public static String buildToken(String id,String password) throws UnsupportedEncodingException {
        return JWT.create().withAudience(id) //将id作为token载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),24)) //24小时后token过期
//                .withExpiresAt(DateUtil.offsetMinute(new Date(),2))//1分钟后token过期
                .sign(Algorithm.HMAC256(SECRET));//password作为token密钥
    }


    /**
     * 验证token 合法性
     */
    public static DecodedJWT verify(String token) throws UnsupportedEncodingException {
        //如果有任何验证异常，此处都会抛出异常
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }



    public static void main(String[] args) throws UnsupportedEncodingException {
//        HashMap<String ,String> map =new HashMap<>();
//        map.put("logname" , "admin");
//
//        String token =  buildToken(map);
//        System.out.println(token);
        String token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2duYW1lIjoiYWRtaW4iLCJleHAiOjE2OTMwMjA0NDF9.MdiuiIm_1IZ-fO7_ZFU1AkA5f7Se6ouRxGwuhg1G--g";
        DecodedJWT  decodedJWT =   verify(token);
    }


}
